<?php

namespace app\api\server;

use app\api\server\Address as ServerAddress;
use app\api\server\Cart as ServerCart;
use app\api\server\Goods as ServerGoods;
use app\api\server\User as ServerUser;
use app\common\controller\Server;
use app\common\library\Auth;
use app\common\model\Cart;
use app\common\model\Circulation;
use app\common\model\CouponLog;
use app\common\model\FounLog;
use app\common\model\goods\Goods as GoodsGoods;
use app\common\model\goods\Review;
use app\common\model\MoneyLog;
use app\common\model\order\Goods;
use app\common\model\order\Order as OrderOrder;
use app\common\model\order\Refund;
use app\common\model\order\Trade;
use app\common\model\performance\Log;
use app\common\model\User;
use app\common\model\user\Address;
use think\Db;
use think\Exception;

/**
 * 订单逻辑
 */
class Order
{

    /**
     * 下单预览
     *
     */
    public static function yu_order($data, $userinfo)
    {
        extract($data);
        try {
            //地址信息
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get($address_id);
                $goods['addressInfo'] = $addressInfo;
                $goods['address_id']  = $address_id;
            } else {
                $addressInfo = ServerAddress::getDefaultAddress($userinfo->id);
                if ($addressInfo) {
                    $goods['addressInfo'] = $addressInfo;
                    $goods['address_id']  = $addressInfo['id'];
                }
            }

            if ($type == 2) {
                $cart_ids = ServerCart::addCart([
                    'goods_id' => $goods_id,
                    'num' => $num,
                    'spec_id' => $spec_id,
                    'class' => $class,
                    'add_sub' => 0,
                ], 2);
            }
            $goods_lists =  ServerCart::getGoods($cart_ids, $userinfo);
            $total_fee = array_sum(array_column($goods_lists, 'total_fee'));
            $pay_fee = array_sum(array_column($goods_lists, 'pay_fee'));
            $goods['coupon_amount'] = $goods['discount_amount']  = $goods['pay_fee'] = 0;
            //优惠券使用
            if (isset($coupon_id) && $coupon_id) {
                $coupon_amount = CouponLog::useCoupon($pay_fee, $coupon_id, $userinfo->id);
                $goods['coupon_amount'] +=  $coupon_amount;
                $coupon_bl = ($pay_fee - $coupon_amount) / $pay_fee;
                // $goods['discount_amount']  += $coupon_amount;
            }
            foreach ($goods_lists as $k => $v) {
                $pay_price = bcmul($v->pay_fee, $coupon_bl ?? 1, 2);
                $v->pay_point = bcmul($pay_price, config('site.point'), 2);
                $v->discount_amount += bcsub($v->pay_fee, $pay_price, 2);
                $v->pay_fee = $pay_price;
                $goods['pay_fee'] += $v->pay_fee;
            }
            //优惠金额
            $goods['discount_amount'] +=  array_sum(array_column($goods_lists, 'discount_amount'));
            $goods['pay_points'] =  array_sum(array_column($goods_lists, 'pay_point'));
            if ($type == 2) {
                Cart::whereIn('id', $cart_ids)->where('user_id', $userinfo['id'])->delete();
            }
            $goods['coupon_id'] = $coupon_id ?? 0;
            $goods['total_fee'] = $total_fee;
            $goods['userInfo'] = $userinfo;
            $goods['goods_lists'] = $goods_lists;
            $goods['total_num'] = array_sum(array_column($goods_lists, 'num'));

            return $goods;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }

    /**
     * 订单下单
     *
     */
    public static function add_order($data)
    {
        extract($data);
        Db::startTrans();
        try {
            if (!isset($address_id) || !$address_id) {
                exception('请选择收货地址');
            }
            if (!isset($goods_lists) || !$goods_lists) {
                exception('请选择购买商品');
            }
            if (isset($goods_lists[0]['goods']['group_id'])) {
                $group_id = $goods_lists[0]['goods']['group_id'];
            }

            $order = OrderOrder::create([
                'user_id' => $userInfo['id'],
                'sn' => sn('order', 'sn', 'NO'),
                'total_num' => $total_num,
                'address_id' => $address_id,
                'contact' => $addressInfo['contact'],
                'telephone' => $addressInfo['telephone'],
                'address' => $addressInfo['detailed_address'],
                'total_fee' =>  $total_fee,
                'pay_points' =>  $pay_points,
                'pay_fee' =>  $pay_fee,
                'discount_amount' => $discount_amount,
                'type' => $class,
                'content' => $content,
                'coupon_id' => $coupon_id,
                'meal' => $meal,
                'group_id' => $group_id ?? 0,
            ], true);
            bcscale(2);
            foreach ($goods_lists as $vv) {
                OrderOrder::check_goods(['id' => $vv['goods_id'], 'num' => $vv['num']]);
                $puser = User::get($userInfo['pid']);
                if ($puser) {
                    if ($puser['group_id'] > 1) {
                        $direct = $vv['goods']['direct'] / 100;
                    } else {
                        $direct = $vv['goods']['vip_direct'] / 100;
                    }
                } else {
                    $direct = $vv['goods']['direct'] / 100;
                }
                $direct = bcmul($vv['pay_fee'], $direct, 2);
                $parallel_grade = $vv['goods']['parallel_grade'] / 100;
                $parallel_grade = bcmul($vv['pay_fee'], $parallel_grade, 2);
                Goods::create([
                    'order_id' => $order['id'],
                    'goods_id' => $vv['goods_id'],
                    'goods_num' => $vv['num'],
                    'goods_name' => $vv['goods']['title'],
                    'direct' => $direct,
                    'parallel_grade' => $parallel_grade,
                    'goods_price' =>  $vv['vip_price'],
                    'personal_reward' =>  $vv['goods']['personal_reward'],
                    'referral_reward' =>  $vv['goods']['referral_reward'],
                    'spec_id' => $vv['spec_id'],
                    'image' =>  $vv['goods']['image'],
                    'subtotal' => $vv['total_fee'],
                    'pay_point' => $vv['pay_point'],
                    'price' =>  bcmul($vv['spec']['price'], $vv['num']),
                    'pay_fee' => $vv['pay_fee'],
                    'primary_agent' => bcmul($vv['spec']['primary_agent'], $vv['num']),
                    'intermediate_agent' => bcmul($vv['spec']['intermediate_agent'], $vv['num']),
                    'advanced_agent' => bcmul($vv['spec']['advanced_agent'], $vv['num']),
                    'county_agent' => bcmul($vv['spec']['county_agent'], $vv['num']),
                    'city_agent' => bcmul($vv['spec']['city_agent'], $vv['num']),
                    'province_agent' => bcmul($vv['spec']['province_agent'], $vv['num']),
                    'first_sensible' => bcmul($vv['spec']['first_sensible'], $vv['num']),
                    'two_sensible' => bcmul($vv['spec']['two_sensible'], $vv['num']),
                    'three_sensible' => bcmul($vv['spec']['three_sensible'], $vv['num']),

                ]);
                ServerGoods::reduceInventory($vv['goods_id'], $vv['spec_id'], $vv['num']);
            }
            Db::commit();
        } catch (\Exception $e) {

            Db::rollback();

            exception($e->getMessage());
        }
        return $order->id;
    }


    //用户订单
    static  function order_list($data)
    {
        extract($data);
        $auth =  Auth::instance();
        $order = new OrderOrder();
        if ($order_status != 'all') {
            $order->where('order_status', $order_status);
        }
        return $order->with(['goods' => function ($q) {
            $q->with(['spec']);
        }])->where('user_id', $auth->id)->order('id desc')->paginate();
    }
    //确认收货
    static public function take_order($data)
    {
        extract($data);
        Db::startTrans();
        try {
            $order = OrderOrder::get($id);
            if ($order->order_status < '20') {
                exception('订单状态错误');
            }
            $order->order_status = '30';
            $order->taketime = time();
            $order->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return true;
    }
    //订单完成添加基金账户明细
    static public function add_fund_account_details($order)
    {
        // 基金池记账倍数
        $fund_pool_ratio = config('site.fund_pool_ratio');

        //共享金入账
        $user = User::get($order->user_id);
        $goods = Goods::all(['order_id' => $order->id]);
        if ($goods) {
            $circulation = Circulation::whereTime('date', 'today')->value('circulation');

            foreach ($goods as $v) {
                //基金统计比例（消费金额*比例）
                if ($v->personal_reward > 0) {
                    $personal_reward = bcmul($v->personal_reward, $fund_pool_ratio, 2);

                    $founLog = FounLog::order('id desc')->find();
                    //个人奖励基金入账
                    FounLog::create([
                        'money' => $personal_reward,
                        'before' => $founLog->after ?? 0,
                        'after' => bcadd($personal_reward, $founLog->after ?? 0, 2),
                        'memo' => '订单完成进入基金账户(个人)',
                        'user_id' => $order->user_id,
                        'order_id' => $order->id,
                    ]);
                    //个人共享金
                    if ($circulation > 0) {
                        $xf_gold = bcdiv($v->personal_reward, $circulation, 5);
                    } else {
                        $xf_gold = 0;
                    }
                    if ($xf_gold > 0) {
                        User::gold(2, $xf_gold, $order->user_id, '订单消费', $order->id);
                    }

                    $user->xfexpiretime = bcadd($user->xfexpiretime, config('site.extra_time') ?? 0, 0);
                    $user->save();
                }
                if ($v->referral_reward > 0 && $user->pid > 0) {
                    $puser = User::get($user->pid);
                    if ($puser) {
                        $referral_reward = bcmul($v->referral_reward, $fund_pool_ratio, 2);
                        $founLog = FounLog::order('id desc')->find();
                        //推荐奖励基金入账
                        FounLog::create([
                            'money' => $referral_reward,
                            'before' => $founLog->after ?? 0,
                            'after' => bcadd($referral_reward, $founLog->after ?? 0, 2),
                            'memo' => '订单完成进入基金账户(推荐)',
                            'user_id' => $order->user_id,
                            'order_id' => $order->id,
                        ]);
                        if ($order->is_first == 1) {
                            $user->xfexpiretime = bcadd($user->tgexpiretime, config('site.extra_time') ?? 0, 0);
                            $puser->save();
                        }
                        if ($circulation > 0) {
                            $tg_gold = bcdiv($v->referral_reward, $circulation, 5);
                        } else {
                            $tg_gold = 0;
                        }
                        if ($tg_gold > 0) {
                            User::gold(1, $tg_gold, $user->pid, '订单推广', $order->id);
                        }
                    }
                }
            }
        }
    }

    static public function goods_evaluate($data)
    {
        extract($data);
        $ids = OrderOrder::where('user_id', $uid)->where('order_status', '30')->column('id');
        $lists = Goods::with(['review'])->whereIn('goods.order_id', $ids)->where('evaluate', $evaluate)->paginate();
        return $lists;
    }
    static public function evaluate($data)
    {
        extract($data);
        Db::startTrans();
        try {
            Review::create([
                'user_id' => $uid,
                'goods_id' => $goods_id,
                'description' => $description,
                'description' => $description,
                'images' => $images,
                'order_id' => $order_id,
                'star' => $star,
                'order_goods_id' => $order_goods_id,
            ]);
            Goods::where('id', $order_goods_id)->update(['evaluate' => 1]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return true;
    }
}
